from flask import request, current_app, jsonify, make_response
import time


class RateThrottle:
    __ERROR_CODE__ = 1003
    cache_format_key = 'throttle_%({0})s_{1}'
    timer = time.time

    def __init__(self, rate, cache):
        self.cache = cache
        self.scope = None
        self.rate = rate
        self.num_requests, self.duration = self.parse_rate(rate=rate)
        self.key = None

    def get_cache_key(self):
        cache_key = self.cache_format_key.format(self.duration, request.remote_addr)
        return cache_key

    def parse_rate(self, rate):
        """
        Given the request rate string, return a two tuple of:
        <allowed number of requests>, <period of time in seconds>
        """
        if rate is None:
            return None, None
        num, period = rate.split('/')
        num_requests = int(num)
        duration = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}[period[0]]
        return num_requests, duration

    def allow_request(self):
        """
        Implement the check to see if the request should be throttled.

        On success calls `throttle_success`.
        On failure calls `throttle_failure`.
        """
        if self.rate is None:
            return True

        self.key = self.get_cache_key()
        self.history = self.cache.get(self.key, [])
        self.now = self.timer()

        while self.history and self.history[-1] <= self.now - self.duration:
            self.history.pop()

        if len(self.history) >= self.num_requests:
            return self.throttle_failure()
        return self.throttle_success()

    def throttle_success(self):
        """
        Inserts the current request's timestamp along with the key
        into the cache.
        """
        self.history.insert(0, self.now)
        self.cache.set(self.key, self.history, self.duration)
        return True

    def throttle_failure(self):
        """
        Called when a request to the API has failed due to throttling.
        """
        return False

    @classmethod
    def rate_throttle_middleware(cls):
        rate = current_app.config.get("RATE_THROTTLE")
        cache = current_app.extensions["cache"]
        throttle = cls(rate, cache)
        success = throttle.allow_request()
        if not success:
            return make_response(jsonify({"code": cls.__ERROR_CODE__, "msg": "您的手速过快请稍后再试"}))
